

/**
 * 设置项数据库操作
 */
use diesel::prelude::*;
use crate::model::setting_model::*;
use crate::schema::settings::dsl::*;

/// Run query using Diesel to find user by uid and return it.
pub fn find_by_id(
    setting_id: &str,
    conn: &SqliteConnection,
) -> Result<Option<Setting>, super::DbError> {

    let setting = settings
        .filter(id.eq(setting_id))
        .first::<Setting>(conn)
        .optional()?;

    Ok(setting)
}

/// Run query using Diesel to insert a new database row and return the result.
#[allow(unused)]
pub fn insert(
    // prevent collision with `name` column imported inside the function
    new_setting: Setting,
    conn: &SqliteConnection,
) -> Result<Setting, super::DbError> {

    diesel::insert_into(settings).values(&new_setting).execute(conn)?;

    Ok(new_setting)
}


/// Run query using Diesel to insert a new database row and return the result.
#[allow(unused)]
pub fn update(
    // prevent collision with `name` column imported inside the function
    new_setting: Setting,
    conn: &SqliteConnection,
) -> Result<Setting, super::DbError> {

    diesel::update(settings.filter(id.eq(&new_setting.id)))
            .set(value.eq(&new_setting.value))
            .execute(conn)?;

    Ok(new_setting)
}


/// Run query using Diesel to insert a new database row and return the result.
pub fn upsert(
    // prevent collision with `name` column imported inside the function
    new_setting: Setting,
    conn: &SqliteConnection,
) -> Result<Setting, super::DbError> {

    let setting_op = settings
        .filter(id.eq(&new_setting.id))
        .first::<Setting>(conn)
        .optional()?;
    if setting_op.is_none() {
        diesel::insert_into(settings).values(&new_setting).execute(conn)?;
    } else {
        diesel::update(settings.filter(id.eq(&new_setting.id)))
            .set(value.eq(&new_setting.value))
            .execute(conn)?;
    }

    Ok(new_setting)
}

#[allow(unused)]
pub fn delete_by_id(
    record_id: &str,
    conn: &SqliteConnection,
) -> Result<(), super::DbError> {
    
    diesel::delete(settings).filter(id.eq(record_id)).execute(conn)?;
    Ok(())
}